package facadeDesignPattern;

/**
 * 
 * @author Anitta
 * Concrete class implementing FacadeInterface and all it's methods. 
 * It is used for button actions from Menu
 * 
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import classes.Employee;
import filterDesignPattern.AdultCriteria;
import filterDesignPattern.YoungCriteria;

public class Functions implements FacadeInterface{
	
	@Override
	public List<Employee> read() {
		List<Employee> list = new ArrayList<Employee>();
		try {

			File f = new File("employee.txt");
			if (!f.exists()) {
				JOptionPane jp = new JOptionPane();
				JOptionPane.showMessageDialog(jp, "File does not exist!");
			} else {
				FileReader fr = new FileReader(f.getName());
				BufferedReader br = new BufferedReader(fr);
				while (true) {
					String line = br.readLine();
					if (line == null) {
						break;
					}
					String[] items = line.split(";");
					Employee e = new Employee();
					e.setFirstName(items[0]);
					e.setLastName(items[1]);
					e.setCity(items[2]);
					e.setAge(Integer.parseInt(items[3]));
					e.setDepartment(items[4]);
					e.setFunction(items[5]);
					e.setSalary(Float.parseFloat(items[6]));
					list.add(e);
				}
				br.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	// throws exception - caught in SaveThread class
	@Override
	public void write(List<Employee> employee) throws Exception {
			File f = new File("employee.txt");
			if (!f.exists()) {
				f.createNewFile();
			}
			FileWriter fw = new FileWriter(f.getName(), true);
			BufferedWriter bw = new BufferedWriter(fw);
			for (Employee e : employee) {
				bw.write(e.toString());
			}
			bw.close();
		}

	@Override
	public List<Employee> youngCriteria() {
		List<Employee> list = new ArrayList<Employee>();
		YoungCriteria youngCriteria = new YoungCriteria();
		list = this.read();
		return youngCriteria.filter(list);
	}

	@Override
	public List<Employee> adultCriteria() {
		List<Employee> list = new ArrayList<Employee>();
		AdultCriteria adultCriteria = new AdultCriteria();
		list = this.read();
		return adultCriteria.filter(list);
	}

	
	}
